<?php

namespace app\admin\controller\mall;

use app\admin\model\MallOrder;
use app\admin\model\MallTradeRecordLog;
use app\admin\model\MallUser;
use app\api\help\SendMsg;
use app\common\controller\AdminController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use think\App;

/**
 * @ControllerAnnotation(title="推广管理")
 */
class Promotion extends AdminController
{
    
    
    public function __construct(App $app)
    {
        parent::__construct($app);
        
        $this->model = new \app\admin\model\MallPromotion();
        
    }
    
    /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            [$page, $limit, $where] = $this->buildTableParames();
            $count      = $this->model
                ->where($where)
                ->count();
            $list       = $this->model
                ->where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->select()->toArray();
            $userIds    = array_column($list, 'user_id');
            $promotions = MallUser::where([['promotion_id', 'in', $userIds]])->field('count(1) as count,promotion_id')->group('promotion_id')->select()->toArray();
            $promotions = array_column($promotions, null, 'promotion_id');
            $tradeLog   = MallTradeRecordLog::where([['user_id', 'in', $userIds], ['trade_type', '=', 17]])->field('user_id,order_id,amount')->select()->toArray();
            $orderIds   = MallTradeRecordLog::where([['user_id', 'in', $userIds], ['trade_type', '=', 17]])->column('order_id');
            $orders     = MallOrder::where([['id', 'in', $orderIds]])->field('id,order_price')->select()->toArray();
            $orders     = array_column($orders, null, 'id');
            foreach ($list as &$value) {
                $value[ 'count' ]       = $promotions[ $value[ 'user_id' ] ][ 'count' ] ?? 0;
                $value[ 'amount' ]      = 0;
                $value[ 'order_num' ]   = 0;
                $value[ 'order_price' ] = 0;
                foreach ($tradeLog as $v) {
                    if ($v[ 'user_id' ] == $value[ 'user_id' ]) {
                        $value[ 'order_num' ]++;
                        $value[ 'amount' ]      += $v[ 'amount' ] ?? 0;
                        $value[ 'order_price' ] += $orders[ $v[ 'order_id' ] ][ 'order_price' ] ?? 0;
                    }
                }
                $value[ 'amount' ]         = getPrice($value[ 'amount' ]);
                $value[ 'promotion_time' ] = $value[ 'promotion_time' ] ? date('Y-m-d H:i:s', $value[ 'promotion_time' ]) : '';
            }
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }
    
    /**
     * @NodeAnotation(title="确认开通")
     */
    public function confirm($id)
    {
        $this->checkPostRequest();
        $row = $this->model->whereIn('id', $id)->find();
        $row->isEmpty() && $this->error('数据不存在');
        try {
            $save = $row->save(['status' => 1, 'promotion_time' => time()]);
            //申请成为推广人成功短信
            $code = 'SMS_461080068';
            if ( !empty($code)) {
                $mobile = MallUser::where('id', $row->user_id)->value('mobile');
                $msg    = [];
                SendMsg::sendMsg($mobile, $msg, $code);
                
            }
        } catch (\Exception $e) {
            $this->error('确认开通失败');
        }
        $save ? $this->success('确认开通成功') : $this->error('确认开通失败');
    }
}